package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.context.UserContext;
import com.example.demo.entity.Comment;
import com.example.demo.entity.CommentLike;
import com.example.demo.entity.User;
import com.example.demo.mapper.CommentLikeMapper;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.CommentService;
import com.example.demo.vo.CommentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Override
    public IPage<CommentVO> getCommentList(Long postId, Integer pageNum, Integer pageSize) {
        // 创建分页对象
        Page<Comment> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getPostId, postId)
                   .eq(Comment::getStatus, 1)
                   .orderByDesc(Comment::getCreateTime);
        
        // 执行分页查询
        IPage<Comment> commentPage = this.page(page, queryWrapper);
        
        // 转换为VO对象并填充用户信息
        IPage<CommentVO> voPage = commentPage.convert(comment -> {
            CommentVO vo = new CommentVO();
            BeanUtils.copyProperties(comment, vo);
            
            // 查询评论发送者信息
            User commentUser = userMapper.selectById(comment.getUserId());
            if (commentUser != null) {
                vo.setUsername(commentUser.getUsername());
                vo.setNickname(commentUser.getNickname());
                vo.setUserAvatar(commentUser.getAvatar() != null ? commentUser.getAvatar() : 
                    "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"); // 设置默认头像
            }
            
            // 如果是回复类型的评论，查询被回复者信息
            if (comment.getReplyToUserId() != null) {
                User replyToUser = userMapper.selectById(comment.getReplyToUserId());
                if (replyToUser != null) {
                    vo.setReplyToUsername(replyToUser.getUsername());
                    vo.setReplyToNickname(replyToUser.getNickname());
                }
            }
            
            return vo;
        });
        
        return voPage;
    }

    @Override
    @Transactional
    public Long createComment(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setLikeCount(0);
        comment.setStatus(1);
        comment.setUserId(UserContext.getUserId());
        this.save(comment);
        return comment.getId();
    }

    @Override
    @Transactional
    public Long replyComment(Comment comment) {
        // 检查父评论是否存在
        Comment parentComment = this.getById(comment.getParentId());
        if (parentComment == null) {
            throw new RuntimeException("父评论不存在");
        }

        // 设置被回复用户ID为父评论的发布者ID
        comment.setUserId(UserContext.getUserId());
        comment.setReplyToUserId(parentComment.getUserId());
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setLikeCount(0);
        comment.setStatus(1);
        this.save(comment);
        return comment.getId();
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId) {
        Comment comment = this.getById(commentId);
        if (comment == null || !comment.getUserId().equals(userId)) {
            return false;
        }

        comment.setStatus(0);
        comment.setUpdateTime(LocalDateTime.now());
        return this.updateById(comment);
    }

    @Override
    @Transactional
    public boolean likeComment(Long commentId, Long userId) {
        // 检查是否已点赞
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getCommentId, commentId)
                   .eq(CommentLike::getUserId, userId);
        if (commentLikeMapper.selectCount(queryWrapper) > 0) {
            return false;
        }

        // 创建点赞记录
        CommentLike like = new CommentLike();
        like.setCommentId(commentId);
        like.setUserId(userId);
        like.setCreateTime(LocalDateTime.now());
        commentLikeMapper.insert(like);

        // 更新评论点赞数
        return this.update()
                .setSql("like_count = like_count + 1")
                .eq("id", commentId)
                .update();
    }

    @Override
    @Transactional
    public boolean unlikeComment(Long commentId, Long userId) {
        // 删除点赞记录
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getCommentId, commentId)
                   .eq(CommentLike::getUserId, userId);
        if (commentLikeMapper.delete(queryWrapper) == 0) {
            return false;
        }

        // 更新评论点赞数
        return this.update()
                .setSql("like_count = like_count - 1")
                .eq("id", commentId)
                .ge("like_count", 1)  // 确保点赞数不会小于0
                .update();
    }
} 